/** @format */

import axios from 'axios'
import router from '@/router'
import store from '@/store' //vuex的路径
import { ElLoading } from 'element-plus'
import '../style/global.css'

// axios.defaults.headers.post['Content-Type'] =
//   'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.timeout = 30000 // 超时时间
axios.defaults.retry = 3 //设置全局请求次数
axios.defaults.retryDelay = 1000 //设置全局请求间隙
axios.defaults.headers.post['isLoading'] = true
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

let loading // 显示loading加载动画
let loadingTimeout = null
// 声明一个对象用于存储请求个数
let needLoadingRequestCount = 0

// 定义一个开启动画的函数
function startLoading() {
  loading = ElLoading.service({
    // loading动画样式
    lock: true,
    customClass: 'createLoading', // 局部class名称
    text: '数据加载中...', //可以自定义文字
    spinner: 'el-icon-loading', //自定义加载图标类名
    background: 'rgba(255, 255, 255, .4)', //遮罩层背景色
  }) //自定义加载动画样式
}
// 定义一个关闭动画的函数
function endLoading() {
  clearTimeout(loadingTimeout)
  loadingTimeout = null
  if (loading !== undefined) {
    loading.close()
  }
}
function tryHideFullScreenLoading() {
  if (needLoadingRequestCount <= 0) {
    return
  }
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    endLoading()
  }
}
// 定义一个不传token的的数组
const noToken = ['/takeon', '/takeoff', '/setrfid', '/getrfid']
// 定义一个不需要加载动画的的的数组
const noLoading = ['/getrfid']

//请求数据拦截器
axios.interceptors.request.use(
  (config) => {
    if (noLoading.some((item) => config.url.includes(item))) {
      store.state.isLoading = false
    } else {
      store.state.isLoading = true //加载Loading加载动画
    }
    //  每次请求之前先进行循环是否是noToken数组中的值，如果有的话就走下面的判断
    if (!noToken.some((item) => config.url.includes(item))) {
      // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
      const token = localStorage.getItem('X-Access-Token')
      token && (config.headers['X-Access-Token'] = token)
    }

    if (store.state.isLoading) {
      if (needLoadingRequestCount === 0) {
        loadingTimeout = setTimeout(() => {
          startLoading()
        }, 800)
      }
      needLoadingRequestCount++
    }
    config.headers.Authorization = localStorage.getItem('')

    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// http响应拦截器  //接收响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.status == 200) {
      store.state.isLoading = false //关闭Loading加载动画
      if (!store.state.isLoading) {
        tryHideFullScreenLoading()
      }
      return Promise.resolve(response)
    } else {
      return Promise.reject(response)
    }
  },
  (error) => {
    if (error.message.includes('timeout')) {
      error.message = '请求服务器超时,请重新连接'
    } else if (error.message.includes('Network Error')) {
      error.message = '网络连接错误，请检查并网络重新连接'
    } else {
      if (error && error.response) {
        switch (error.response.status) {
          case 400:
            error.message = '请求错误(400)'
            break
          case 401:
            error.message = '登录状态已过期，请重新登录'
            router.replace({
              path: '/',
            })
            // 删除缓存
            localStorage.removeItem('X-Access-Token')
            localStorage.removeItem('userName')
            localStorage.removeItem('accountld')
            localStorage.removeItem('loginName')
            break
          case 403:
            error.message = '拒绝访问(403)'
            router.replace({
              path: '/',
            })
            break
          case 404:
            error.message = '请求出错(404)'
            break
          case 408:
            error.message = '请求超时(408)'
            break
          case 500:
            error.message = '服务器错误(500)'
            break
          case 501:
            error.message = '服务未实现(501)'
            break
          case 502:
            error.message = '网络错误(502)'
            break
          case 503:
            error.message = '服务不可用(503)'
            break
          case 504:
            error.message = '网络超时(504)'
            break
          case 505:
            error.message = 'HTTP版本不受支持(505)'
            break
          default:
            error.message = `连接出错(${error.response.status})!`
        }
      }
    }
    // 响应后则清除定时器、关闭加载动画
    tryHideFullScreenLoading()

    // message.error(error.message);
    return Promise.reject(error)
  }
)

export default axios
